/*
 * @Description: axios
 * @Author: oscar
 * @Date: 2021-12-09 21:19:39
 */
import { getApiKey, getWhiteApi } from "@/utils/http/config";
import { getSign } from "@/utils/http/sign";
import { getToken } from "@/utils/auth/index";
import { ElMessageBox, ElMessage } from "element-plus";

import * as axios from "axios";
import * as EventEmitter from 'events';

class Request extends EventEmitter {
  constructor() {
    super();
    this.interceptors();
  }
  interceptors() {
    // 请求拦截器
    axios.interceptors.request.use(
      // 发送请求之前
      config => {
        // 设置 签名
        let signData = {}
        let apiKey = getApiKey()
        if( config.method === 'get') {
          signData = config.params
        } else if( config.method === 'post') {
          signData = config.data // JSON.parse(config.data)
        }
        config.headers.sign = getSign(signData, apiKey)
        // 设置 token
        config.headers.token = getToken() || 'oscar'
        return config;
      },
      error => {
        // 请求错误
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    axios.interceptors.response.use(
      response => {
        const code = response.status;
        if ((code >= 200 && code < 300) || code === 304) {
          const res = response.data
          if(res.code !== 0) {
            dialogMessage(res.message)
            if(res.code === 401) { // token 过期
              window.localStorage.clear()
              window.location.href = '/login'
            }
          } else {
            this.emit("Success");
            return Promise.resolve(res.data);
          }
        } else {
          console.log(response)
          // 响应错误逻辑处理 5xx 4xx 等等
          this.emit("Error");
          return Promise.reject(response);
        }
      },
      error => {
        // 响应错误逻辑处理
        console.log(error);
        dialogMessage(error.message)
        this.emit("Error");
        return Promise.reject(error);
      }
    );
  }
  get(url, params) {
    return axios({
      method: 'get',
      url,
      params
    });
  }
  post(url, data) {
    return axios({
      method: 'post',
      url,
      data
    });
  }
  delete(url, data) {
    return axios({
      method: 'delete',
      url,
      data
    });
  }
  put(url, data) {
    return axios({
      method: 'put',
      url,
      data
    });
  }
  patch(url, data) {
    return axios({
      method: 'patch',
      url,
      data
    });
  }
}


const dialogMessage = (message) => {
  console.log(message)
  if (!message) {
    return
  }
  // 判断企业微信的状态
  if (message.includes('work.weixin.qq.com')) {
    if (message.includes('41054')) {
      ElMessageBox.alert('有人未激活企业微信', '出错了', {
        confirmButtonText: '确定'
      })
    } else {
      ElMessage.error('导购异常，请联系客服' + message)
    }
  } else {
    ElMessage.error(message)
  }
}

let request = new Request();
export default request;
